﻿using UnityEngine;
using System.Collections;
using MoreMountains.Tools;

namespace MoreMountains.CorgiEngine
{
    /// Animator parameters : NormalAtk
    public class CharacterNormalAttack : CharacterAbility
    {
        public enum AtkNum { None, A1, A2, A3 }
        public override string HelpBoxText() { return "基础三段攻击"; }

        [Header("NormalAttack ")]

        public AtkNum CurrentAtkNum = AtkNum.None;

        //  是否只能在地面使用
        public bool OnlyCanUseInGroud = false;
        [SerializeField]
        //  是否可以继续攻击
        private bool _ContinouAtk = true;

        [SerializeField]
        private float _Ground_X_SlowDown = 0.38f;
        [SerializeField]
        private float _Air_X_SlowDown = 0.5f;

        [SerializeField]
        /// <summary> 下落时的Y轴加速度 </summary>  
        public float Air_Y_Acceleration = -0.75f;

        //  记录的最后一个按键
        public static MMInput.IMButton LastButton = null;

        //protected float _cooldownTimeStamp = 0;

        [Header(" ")]
        [SerializeField]
        private WaitForSeconds _WaitTime = new WaitForSeconds(0.35f);

        [SerializeField]
        /// <summary> 攻击锁 </summary>  
        private bool LockAtkFlag = false;

        public DamageInfo DamageInfo = new DamageInfo(20);

        protected override void Initialization()
        {
            base.Initialization();
            _inputManager.OnAnyKeyDown += OnAnyKeyDownListener;
        }

        protected override bool CheckHandleInput()
        {
            return _inputManager.NormalAtkButton.State.CurrentState == MMInput.ButtonStates.ButtonDown &&
               (_inputManager.PrimaryMovement.y > -_inputManager.Threshold.y || _controller.State.IsGrounded == true) &&
               (_inputManager.PrimaryMovement.y < _inputManager.Threshold.y || _controller.State.IsGrounded == false);
        }
        /// <summary>
        /// At the start of each cycle, we check if we're pressing the dash button. If we
        /// </summary>
        protected override void HandleInput()
        {
            StartAtk();
        }


        /// <summary>
        /// The second of the 3 passes you can have in your ability. Think of it as Update()
        /// </summary>
        public override void ProcessAbility()
        {
            base.ProcessAbility();
            // If the character is NormalAtk, we cancel the gravity
            if (_movement.CurrentState == CharacterStates.MovementStates.NormalAtk)
            {
                _controller.GravityActive(false);
                _controller.SetVerticalForce(Air_Y_Acceleration * (3 + (int)CurrentAtkNum * 0.5f));         //  攻击过程  空中下降速度控制
                if (CurrentAtkNum == AtkNum.A3)
                {
                    _controller.GravityActive(true);
                    _controller.SetVerticalForce(Air_Y_Acceleration * 8);         //  攻击过程  空中下降速度控制
                }
            }
            if (_controller.State.IsGrounded && _ContinouAtk == false)
                _ContinouAtk = true;
        }

        private void OnAnyKeyDownListener(MMInput.IMButton button)
        {
            LastButton = button;
        }

        /// <summary>
        /// Causes the character to dash or dive (depending on the vertical movement at the start of the dash)
        /// </summary> 
        public virtual void StartAtk()
        {
            // if the Dash action is enabled in the permissions, we continue, if not we do nothing
            if (!AbilityPermitted
                || (_condition.CurrentState != CharacterStates.CharacterConditions.Normal)
                || (_movement.CurrentState == CharacterStates.MovementStates.Gripping))
                return;

            if (OnlyCanUseInGroud && _controller.State.IsGrounded == false)
                return;

            //  不再检测这个  空中会自由下落
            //if (_ContinouAtk == false)
            //    return;


            // if the character is allowed to dash
            if (LockAtkFlag == false)
            {
                // we set its Atk state to true
                _movement.ChangeState(CharacterStates.MovementStates.NormalAtk);

                // 播放音效
                PlayAbilityStartSfx();
                PlayAbilityUsedSfx();
                // we launch the boost corountine with the right parameters
                StartCoroutine(NormalAttack());
                _ContinouAtk = false;
            }
        }
        protected virtual IEnumerator NormalAttack()
        {
            if (!AbilityPermitted
              || _condition.CurrentState != CharacterStates.CharacterConditions.Normal)
            {
                yield break;
            }
            //  禁用InputMgr控制
            ControlInput(false);
            //  清空缓存按键
            LastButton = null;
            //  为攻击加锁
            LockAtkFlag = true;
            if (CurrentAtkNum == AtkNum.A3)
                CurrentAtkNum = AtkNum.A1;
            else
                CurrentAtkNum = CurrentAtkNum + 1;

            //  设置为浮空
            _controller.GravityActive(false);
            //  保留一部分横向速度，竖向速度为0
            _controller.SetHorizontalForce(_controller.Speed.x * (_controller.State.IsGrounded ? _Ground_X_SlowDown : _Air_X_SlowDown));
            //_controller.SetVerticalForce(0);

            //  设置攻击力
            _character.AttackColliderScript.SetDamage(CalcDamageInfo());

            yield return _WaitTime;
            if (_condition.CurrentState == CharacterStates.CharacterConditions.Normal && _movement.CurrentState == CharacterStates.MovementStates.NormalAtk)
            {
                //  最后一个按键是攻击，就继续       此处A3就别继续了  重新开始吧。
                if (LastButton == _inputManager.NormalAtkButton && CurrentAtkNum != AtkNum.A3)
                {
                    StartCoroutine(NormalAttack());
                    yield break;
                }
            }
            // 播放退出音效
            StopAbilityUsedSfx();
            PlayAbilityStopSfx();
            ResetOthers();
        }

        private void ResetOthers()
        {
            //重置攻击力
            _character.AttackColliderScript.Reset();
            //  取消人物悬浮
            _controller.GravityActive(true);
            //  设置状态为初始值
            CurrentAtkNum = AtkNum.None;
            //  关掉攻击锁
            LockAtkFlag = false;
            
            if (_movement.CurrentState == CharacterStates.MovementStates.NormalAtk)
            {
                //_movement.RestorePreviousState();
                _movement.ChangeState(CharacterStates.MovementStates.Idle); //  我设置成了变成站立。
            }
            //  恢复InputMgr控制
            ControlInput(true);

        }

        /// <summary>
        /// Adds required animator parameters to the animator parameters list if they exist
        /// </summary>
        protected override void InitializeAnimatorParameters()
        {
            RegisterAnimatorParameter("NormalAtk" + (int)AtkNum.A1, AnimatorControllerParameterType.Bool);
            RegisterAnimatorParameter("NormalAtk" + (int)AtkNum.A2, AnimatorControllerParameterType.Bool);
            RegisterAnimatorParameter("NormalAtk" + (int)AtkNum.A3, AnimatorControllerParameterType.Bool);
        }

        /// <summary>
        /// At the end of the cycle, we update our animator's Dashing state 
        /// </summary>
        public override void UpdateAnimator()
        {
            bool attacking = _movement.CurrentState == CharacterStates.MovementStates.NormalAtk;
            MMAnimator.UpdateAnimatorBool(_animator, "NormalAtk" + (int)AtkNum.A1, attacking && CurrentAtkNum == AtkNum.A1, _character._animatorParameters);
            MMAnimator.UpdateAnimatorBool(_animator, "NormalAtk" + (int)AtkNum.A2, attacking && CurrentAtkNum == AtkNum.A2, _character._animatorParameters);
            MMAnimator.UpdateAnimatorBool(_animator, "NormalAtk" + (int)AtkNum.A3, attacking && CurrentAtkNum == AtkNum.A3, _character._animatorParameters);
        }

        protected override DamageInfo CalcDamageInfo()
        {
            return DamageInfo;
        }

    }
}